package com.vogue.supplymall.admin.business.controller;

import com.vogue.supplymall.account.domain.model.AdminUser;
import com.vogue.supplymall.admin.business.common.OpenOrganCheckUtils;
import com.vogue.supplymall.admin.business.common.constant.ErrorCode;
import com.vogue.supplymall.admin.business.domain.biz.OrganManagementBiz;
import com.vogue.supplymall.admin.business.domain.biz.TaskProcessorBiz;
import com.vogue.supplymall.admin.business.exception.AdminProcessException;
import com.vogue.supplymall.admin.business.exception.OpenOrganException;
import com.vogue.supplymall.common.domain.dto.ControllerResultInfo;
import com.vogue.supplymall.common.domain.dto.admin.OrganManagementInfo;
import com.vogue.supplymall.common.exception.ParamErrorException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * The type organ management controller
 * 集团管理的controller.
 *
 * @aouthor: zhangliang
 * @date: Create in 2018-04-27
 */
@RestController
public class OrganManagementController extends BaseController {
    /**
     * The constant log.
     */
    public static final Logger LOGGER_ORGANMANAGEMENTCONTROLLER = LoggerFactory.getLogger(OrganManagementController.class);
    @Resource
    private OrganManagementBiz organManagementBiz;
    @Resource
    private TaskProcessorBiz taskProcessorBiz;

    /**
     * Gets organ list.
     * 已开通集团列表（只要开通过就是已开通集团）
     *
     * @param appver         the appver
     * @param managementInfo the management info
     * @return the organ list
     */
    @RequestMapping(value = "/is/{appver}/admin/business/isopen/organ/list", method = RequestMethod.POST)
    public ResponseEntity<Object> getOrganList(@PathVariable("appver") String appver, @RequestBody OrganManagementInfo managementInfo) {
        LOGGER_ORGANMANAGEMENTCONTROLLER.info("get Organ List start >>>>>> ");
        OpenOrganCheckUtils.checkOpendOrganList(managementInfo);
        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setResult(true);
        resultInfo.setData(organManagementBiz.getOrganList(managementInfo));
        LOGGER_ORGANMANAGEMENTCONTROLLER.info(" <<<<<< get Organ List  end");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }

    /**
     * Onoff organ response entity.
     * 启用停用集团
     *
     * @param appver         the appver
     * @param managementInfo the management info
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/admin/business/organ/onoff", method = RequestMethod.POST)
    public ResponseEntity<Object> onoffOrgan(@PathVariable("appver") String appver, @RequestBody OrganManagementInfo managementInfo) {
        LOGGER_ORGANMANAGEMENTCONTROLLER.info("onoff Organ start >>>>>> ");
        Boolean result;
        try {
            organManagementBiz.doOnOffOrgan(managementInfo);
            result = taskProcessorBiz.doOnoffOrgan();
        } catch (RuntimeException re) {
            throw new AdminProcessException(ErrorCode.ProcessFail.getCode(), ErrorCode.ProcessFail.getMsg());
        }

        if (!result) {
            throw new OpenOrganException("");
        }
        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setResult(true);
        resultInfo.setData(null);
        LOGGER_ORGANMANAGEMENTCONTROLLER.info(" <<<<<< onoff Organ  end");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }


    /**
     * Organ recharge response entity.
     * 查询账本信息
     *
     * @param appver         the appver
     * @param managementInfo the management info
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/admin/business/organ/accountbook", method = RequestMethod.POST)
    public ResponseEntity<Object> searchAccountBook(@PathVariable("appver") String appver, @RequestBody OrganManagementInfo managementInfo) {
        LOGGER_ORGANMANAGEMENTCONTROLLER.info("search account book start >>>>>> ");
        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setResult(true);
        resultInfo.setData(organManagementBiz.searchAccountBook(managementInfo.getOrganid()));
        LOGGER_ORGANMANAGEMENTCONTROLLER.info(" <<<<<< search account book end");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }

    /**
     * Onoff organ response entity.
     * 集团充值
     *
     * @param appver         the appver
     * @param managementInfo the management info
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/admin/business/organ/recharge", method = RequestMethod.POST)
    public ResponseEntity<Object> doOrganRecharge(@PathVariable("appver") String appver, @RequestBody OrganManagementInfo managementInfo) {
        LOGGER_ORGANMANAGEMENTCONTROLLER.info("organ recharge start >>>>>> ");
        AdminUser info = new AdminUser();
        if (SecurityUtils.getSubject().isAuthenticated()) {
            info = (AdminUser) SecurityUtils.getSubject().getPrincipal();
            LOGGER_ORGANMANAGEMENTCONTROLLER.info("获取登信息：" + info.getLoginname());
            if (StringUtils.isEmpty(managementInfo.getAmount()) || StringUtils.isEmpty(managementInfo.getDiscount())) {
                throw new ParamErrorException("");
            }
        } else {
            LOGGER_ORGANMANAGEMENTCONTROLLER.info("获取登信息失败！");
        }
        try {
            organManagementBiz.doOrganRecharge(managementInfo, info);
        } catch (RuntimeException re) {
            throw new AdminProcessException(ErrorCode.ProcessFail.getCode(), ErrorCode.ProcessFail.getMsg());
        }

        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setResult(true);
        resultInfo.setData(null);
        LOGGER_ORGANMANAGEMENTCONTROLLER.info(" <<<<<< organ recharge end");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }

    /**
     * Search config response entity.
     * 查询配置方案
     *
     * @param appver         the appver
     * @param managementInfo the management info
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/admin/business/organ/config/search", method = RequestMethod.POST)
    public ResponseEntity<Object> searchConsumeConfig(@PathVariable("appver") String appver, @RequestBody OrganManagementInfo managementInfo) {
        LOGGER_ORGANMANAGEMENTCONTROLLER.info(" search config start >>>>>> ");
        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setResult(true);
        try {
            Map<String, Object> data = organManagementBiz.searchConsumeConfig(managementInfo);
            resultInfo.setData(data);
        } catch (RuntimeException ex) {
            throw new AdminProcessException(ErrorCode.ProcessFail.getCode(), ErrorCode.ProcessFail.getMsg());
        }

        LOGGER_ORGANMANAGEMENTCONTROLLER.info(" <<<<<< search config end");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }

    /**
     * Update config response entity.
     * 改配--提交
     *
     * @param appver         the appver
     * @param managementInfo the management info
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/admin/business/organ/config/update", method = RequestMethod.POST)
    public ResponseEntity<Object> updateConsumeConfig(@PathVariable("appver") String appver, @RequestBody OrganManagementInfo managementInfo) {
        LOGGER_ORGANMANAGEMENTCONTROLLER.info(" update config start >>>>>> ");
        AdminUser info = new AdminUser();
        if (SecurityUtils.getSubject().isAuthenticated()) {
            info = (AdminUser) SecurityUtils.getSubject().getPrincipal();
            LOGGER_ORGANMANAGEMENTCONTROLLER.info("获取登信息：" + info.getLoginname());
            if (OpenOrganCheckUtils.apply(managementInfo) || null == managementInfo.getOrganid()
                    || null == managementInfo.getBalanceId()) {
                throw new ParamErrorException("");
            }
        } else {
            LOGGER_ORGANMANAGEMENTCONTROLLER.info("获取登信息失败！");
        }

        try {
            organManagementBiz.updateConsumeConfig(managementInfo, info);
        } catch (RuntimeException re) {
            throw new AdminProcessException(ErrorCode.ProcessFail.getCode(), ErrorCode.ProcessFail.getMsg());
        }

        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setResult(true);
        resultInfo.setData(null);
        LOGGER_ORGANMANAGEMENTCONTROLLER.info(" <<<<<< update config end");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }
}
